<template>
  <el-container>

    <el-main>
      <!-- 查询条件 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="锁定" value="锁定"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleAdd">新增用户</el-button>
        </el-form-item>
      </el-form>

      

      <!-- 用户列表 -->
      <el-table
        :data="userList"
        border
        style="width: 100%"
        height="600"
      >
         

        <!-- 其他列 -->
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="realname" label="真实姓名" width="120"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
        <el-table-column prop="address" label="地址" width="200"></el-table-column>
        <el-table-column prop="department" label="部门" width="120"></el-table-column>
        <el-table-column prop="rolenames" label="角色" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="80"></el-table-column>
        <el-table-column prop="createtime" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="updatetime" label="更新时间" width="150"></el-table-column>
        <el-table-column prop="lastlogintime" label="最后登录时间" width="150"></el-table-column>
        <el-table-column prop="idcard" label="身份证号" width="180"></el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
        <el-table-column prop="education" label="学历" width="100"></el-table-column>
        <el-table-column prop="occupation" label="职业" width="120"></el-table-column>
        <el-table-column prop="company" label="公司" width="150"></el-table-column>
        <el-table-column prop="position" label="职位" width="120"></el-table-column>

        <!-- 操作列固定在左侧 -->
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
            <el-button size="small" @click="handleResetPassword(scope.row.id)">重置密码</el-button>
            <el-button size="small" @click="handleUnlock(scope.row.id)" v-if="scope.row.status === '锁定'">解锁</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum" 
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>

      <!-- 新增/修改用户对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="form.realname"></el-input>
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
              <el-option label="未知" value="未知"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="form.address"></el-input>
          </el-form-item>
          <el-form-item label="部门">
            <el-select v-model="form.department" placeholder="请选择部门">
              <el-option
                v-for="dept in departmentOptions"
                :key="dept.value"
                :label="dept.label"
                :value="dept.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="正常" value="正常"></el-option>
              <el-option label="锁定" value="锁定"></el-option>
              <el-option label="禁用" value="禁用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角色">
            <el-transfer
              v-model="selectedRoleIds"
              :data="roleOptions"
              :titles="['可选角色', '已选角色']"
              filterable
            ></el-transfer>
          </el-form-item>
          
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import request from '../utils/request';

// 模拟数据
const departmentOptions = [
  { label: '技术部', value: '技术部' },
  { label: '市场部', value: '市场部' },
  { label: '财务部', value: '财务部' },
];

const roleOptions = ref([]); // 角色选项

// 查询参数
const queryParams = ref({
  username: '',
  phone: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
});

// 用户列表数据
const userList = ref([]);
const total = ref(0); // 总条数
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref('新增用户'); // 对话框标题
const form = ref({
  id: '',
  username: '',
  realname: '',
  password:'',
  gender: '',
  birthday: '',
  phone: '',
  email: '',
  address: '',
  department: '',
  roleid: [],
  status: '正常',
});

// 获取用户列表
const fetchUserList = async () => {
  try {
      debugger;
    const response = await request.post("/sys/user/queryPage", queryParams.value);
    userList.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await request.post('/sys/role/queryPage', {});
    roleOptions.value = response.data.records.map(role => ({
      key: role.id,
      label: role.name,
    }));
  } catch (error) {
    ElMessage.error('获取角色列表失败');
  }
};

// 查询用户列表
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  fetchUserList();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    username: '',
    phone: '',
    status: '',
    pageNum: 1,
    pageSize: 10,
  };
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (size) => {
  queryParams.value.pageSize = size;
  fetchUserList();
};

// 分页页码改变
const handlePageChange = (page) => {
  queryParams.value.pageNum = page;
  fetchUserList();
};

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户';
  form.value = {
    id: '',
    username: '',
    realname: '',
    password:'',
    gender: '',
    birthday: '',
    phone: '',
    email: '',
    address: '',
    department: '',
    roleid: [],
    status: '正常',
  };
  dialogVisible.value = true;
};
const selectedRoleIds = ref([]);
// 修改用户
const handleEdit = (row) => {
  dialogTitle.value = '修改用户';
  //form.value = { ...row };
debugger;
selectedRoleIds.value = row.roleid.split(',').map(id => Number(id));
form.value=row;
//   form.value = { 
//   ...row,
//   roleid: selectedRoleIds, // 将 roleid 转换为数组
// };
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该用户吗？', '提示', { type: 'warning' });
    await request.post('/sys/user/delete', { id });
    ElMessage.success('删除成功');
    fetchUserList();
  } catch (error) {
    // 用户取消删除
  }
};

// 解锁用户
const handleUnlock = async (id) => {
  try {
    await ElMessageBox.confirm('确定解锁该用户吗？', '提示', { type: 'warning' });
    const rel = await request.post('/sys/user/unlock', { id });
    if(rel.data.code == 200){
      ElMessage.success(rel.data.message);
    }else{
      ElMessage.error(rel.data.message);
    }
    
    fetchUserList();
  } catch (error) {
    // 用户取消解锁
  }
};

// 重置密码
const handleResetPassword = async (id) => {
  try {
    await ElMessageBox.confirm('确定重置该用户的密码吗？', '提示', { type: 'warning' });
    const rel =   await request.post('/sys/user/resetPassword', { id });
    if(rel.data.code == 200){
      ElMessage.success(rel.data.message);
    }else{
      ElMessage.error(rel.data.message);
    }
  } catch (error) {
    // 用户取消重置
  }
};

// 提交表单
const submitForm = async () => {
  try {
    debugger;
    roleOptions.value;
    const url = form.value.id ? '/sys/user/update' : '/sys/user/create';
    form.value.roleid = selectedRoleIds.value.join(',');
    await request.post(url, form.value);
    form.value.roleid = "";
    ElMessage.success('操作成功');
    dialogVisible.value = false;
    fetchUserList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

onMounted(() => {
  fetchUserList();
  fetchRoleList();
});
</script>

<style scoped>
.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
}
</style>
